﻿ using System;
using System.Net.Sockets;

namespace Yuki.Sockets
{
    public class YukiSocketClient
    {
        public byte[] Buffer;
        public bool Connected;
        private Socket connection;
        public IPacketCipher Crypto;
        public int RecvSize;
        private ServerSocket server;
        public SocketEvent<YukiSocketClient, object> SocketCorrupt;
        private static uint socketUID;
        private uint UID;
        public object Wrapper;

        public YukiSocketClient(ServerSocket _Server, Socket _Connection, int BufferSize)
        {
            this.server = _Server;
            this.connection = _Connection;
            this.UID = socketUID++;
            this.Buffer = new byte[BufferSize];
            this.RecvSize = 0;
            this.Wrapper = null;
        }

        public void Disconnect()
        {
            try
            {
                this.Connection.Disconnect(false);
            }
            catch
            {
                this.Server.InvokeDisconnect(this);
            }
        }

        public bool Send(byte[] Packet)
        {
            try
            {
                if (this.Crypto != null)
                {
                    byte[] dest = new byte[Packet.Length];
                    this.Crypto.Encrypt(Packet, dest, dest.Length);
                    this.connection.Send(dest);
                }
                else
                {
                    this.connection.Send(Packet);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public Socket Connection
        {
            get
            {
                return this.connection;
            }
        }

        public ServerSocket Server
        {
            get
            {
                return this.server;
            }
        }

        public uint UniqueID
        {
            get
            {
                return this.UID;
            }
        }
    }
}

